var val = function() {return [
	'httpd',
	function(_) {
		var bodyParser = require('body-parser');
		var express = require('express');
		var app = express();
		app.use(bodyParser.text({ type: 'text/plain' }));
		_('~Status')(':set', 'app', app);
		app.use('/myhttpd', express.static('htdocs'));
		var server = app.listen(3000,
		function() {
			var host = server.address().address;
			var port = server.address().port;
			console.log('Example app listening at http://%s:%s', host, port);
		});
	},
	'api',
	function(_){
		_.JSON5=_('/Tool/JSON5')();
		var tp=_;
		_.th_id_allocated=0;
		_.all=function(){
			if(_.app&&_.Dbroot)
				_('#ready')();
		}
		_.enum_thread=function(_,val){
			switch(this.keys[0]){
				case 'start':
				_.result={};
				_.all=function(){
					if(_.result.val!==undefined&&_.result.enum!==undefined)
						_('#all-done')();
				};
				if(this.ext.query.method===':enum-val'){
					this.ext.db.child(_,'#get_child',this.ext.query.location);
				};
				break;
				case 'get_child':
				val.enum_child(_,'#get_child_enum_child_last');
				val.val(':get',_,'#get_child_val_last');
				break;
				case 'get_child_enum_child_last':
				_.result.enum=val;
				_.all();
				break;
				case 'get_child_val_last':
				_.result.val=val;
				_.all();
				break;
				case 'all-done':
				this.ext.res.end(tp.JSON5.stringify(_.result));
				_('!x_x')();
				break;
			}
		};
		_.exist_thread=function(_,val){
			switch(this.keys[0]){
				case 'start':
				this.ext.db.exist(_,'#exist_flag',this.ext.query.location);
				break;
				case 'exist_flag':
				this.ext.res.end(tp.JSON5.stringify({res:val}));
			};
		};
		//_.tp=_('/Permond','!_');
		
		_('~Status')(':wait','app',null,'#app');
		_('~Status')(':wait','Dbroot',null,'#Dbroot');
		_('!#=')(function(_,val){
			switch(this.keys[0]){
				case 'app':
				_.app=val;
				_.all();
				break;
				case 'Dbroot':
				_.Dbroot=val;
				_.all();
				break;
				case 'ready':
				_.app.post('/api', function (req, res) {
					var req_info=_.JSON5.parse(req.body);
					if(req_info.get==='tree'){
						switch(req_info.method){
						case ':enum-val':
							var thread_msgr=_('/Tool/rebind')(_.enum_thread,'ext',{query:req_info,db:_.Dbroot,res:res});
							_(''+_.th_id_allocated,'!#=')(thread_msgr);
							_(''+_.th_id_allocated,'#start')();
							_.th_id_allocated++;
							break;
						case ':exist':
							var thread_msgr=_('/Tool/rebind')(_.exist_thread,'ext',{query:req_info,db:_.Dbroot,res:res});
							_(''+_.th_id_allocated,'!#=')(thread_msgr);
							_(''+_.th_id_allocated,'#start')();
							_.th_id_allocated++;
							break;
						}
					};
					//_()();
					/*
					var js='_.tp'+"(_,'#val"+_.id_count+"\'"+req.originalUrl.split('/api?c=_(')[1];
					_.creq=[id_count]=res;
					eval(js);
					*/
				});
				break;
			}
			
		});
	},
	'Db',
	function(_) {
		function toNumber(number){
			var times=0;
			var i=number;
			while(i>10){
    			i=i/10;
    			times++;
			};

			var str=(''+number);
			for(;times<10;times++){
				str='0'+str;
			}
			return str;
		};
		_.all = function() {
			if (_.keytoval && _.nodetable && _.config) _('#ready')();
		};
		var tiny = require('tiny');
		tiny('./local/keytoval.tiny',
		function(err, db) {
			if (err) {
				console.log(err);
				throw err;
			} else {
				_.keytoval = db;
				_.all();
			}
		});
		tiny('./local/nodetable.tiny',
		function(err, db) {
			if (err) {
				console.log(err);
				throw err;
			} else {
				_.nodetable = db;
				_.all();
			}
		});
		tiny('./local/config.tiny',
		function(err, db) {
			if (err) {
				console.log(err);
				throw err;
			} else {
				_.config = db;
				_.all();
			}
		});
		_('!#=')(function(_, val) {
			switch (this.keys[0]) {
			case 'ready':
				_.config.get('id_allocated',
				function(err, data) {
					if (err) {
						console.log('config error');
						_.config.set('id_allocated', {
							val: 0
						},
						function(err) {
							console.log('set config error')
						});
					} else {
						_('#id_allocated')(data.val);
					}

				});
				/*
				process.on('SIGINT', function() {
					_.config.set('id_allocated',{val:_.node.prototype.id_allocated[0]},function(err){
						if(err)
							console.log(err);
						process.exit();
					});
					console.log(6666);
					return true;
					//console.log('Got SIGINT.  Press Control-D/Control-C to exit.');
				});
				*/
			break;
			case 'id_allocated':
				_.node = function(id) {
					this.id = id;
				};
				_.node.prototype.getValByID = function(id, val, way) {

				};
				_.node.prototype.id_allocated = [val];
				_.node.prototype.keytoval = _.keytoval;
				_.node.prototype.nodetable = _.nodetable;
				_.node.prototype.config = _.config;
				_.node.prototype.val = function(method, _, way, val) {
					var tp=this;
					switch (method) {
					case ':get':
						this.keytoval.get(toNumber(this.id),
						function(err, data) {
							if (data === undefined) _(way)(null);
							else _(way)(data.val)
						});
						break;
					case ':set':
						this.keytoval.update(toNumber(this.id), {
							val: val,
						},
						function(err) {
							tp.val(':set2', _, way, val);
						});
						break;
					case ':set2':
						this.keytoval.set(toNumber(this.id), {
							val: val,
						},
						function(err) {
							if(err)console.log('daruis set unknown error');
						});
						break;
					};
						
				};
				var tp = _;
				_.node.prototype.__next = function(_, way, now_location,location, flag, okid) {
					var ths=this;
					if (flag === 'get') {
						this.nodetable.get(now_location + (toNumber(this.id)),
						function(err, data) {
							if (err) {
								ths.__next(_, way, now_location, location, 'set');
							} else {
								ths.__next(_, way, now_location,location, 'ok', data.id);
							}
						});
					} else if (flag === 'set') {
						this.id_allocated[0]++;
						var val_id=this.id_allocated[0];
						this.nodetable.set(now_location + (toNumber(this.id)), {
							id: val_id,
							parent_id:this.id,
						},
						function(err, data) {
							if (err) {
								console.log('Collision', err);
								ths.__next(_, way, now_location, location,'get');
							} else {
								ths.__next(_, way, now_location, location, 'ok', val_id);
							}
						})
					} else if (flag === 'ok') {
						if (location.length === 0) {
							_(way)((new tp['node'](okid)));
						} else {
							var n_node=new tp['node'](okid);
							var now_location=location.shift();
							n_node.__next(_, way, now_location,location, 'get');
						}
					}
				};
				_.node.prototype.enum_child=function(_,way){
					var childs=[];
					this.nodetable.find({parent_id:this.id}, function(err, results) {
						if(err) {
							console.log('enum_child error');
							return 0;
						}
						for(var i =0,len=results.length;i<len;i++)
  				 		{
  				 			var temp_key=results[i]._key;
  				 			temp_key=temp_key.substring(0,temp_key.length-11);
  				 			childs.push(temp_key);
  				 		};
  				 		_(way)(childs);
			  		});
				};
				_.node.prototype.child = function(_, way, location) {
					var now_location=location.shift();
					this.__next(_, way, now_location, location,'get',null);
				};
				_.node.prototype.exist=function(_,way,location){
					var now_location=location.shift();
					this.exist__next(_,way,now_location,location);
				};
				_.node.prototype.exist__next=function(_,way,now_location,location){
					this.nodetable.get(now_location + (toNumber(this.id)),function(err){
							if (err) {
								_(way)(false);
							} else {
								if(location.length===0){
									_(way)(true);
									return 0;
								}
								now_location=location.shift();
								ths.exist__next(_, way, now_location,location);
							}
					});
				};
				_.node.prototype.setValByID = function(id, val, way) {};
				_.Dbroot = new _['node'](0);
				_('~Status')(':set', 'Dbroot', _.Dbroot, null);
				break;
			};
		});
	},
	/*
	'get-init-data',
	function(_){
		_('~Status')(':wait','Dbroot',null,'#Dbroot');
		console.log(66);
		_('!#=')(function(_,val){
			switch(this.keys[0]){
				case 'Dbroot':
				_.Dbroot=val;
				_.Dbroot.child(_,'#localroot',['zsad','asdasdsfa','asda']);
				break;
				case 'localroot':
				var node=val;
				node.val(':set',_,'#zzz','6666');
				node.val(':get',_,'#zzz','6666');
				break;
				case 'get':
				console.log('12e3');
				break;
				case 'zzz':
				 console.log('real 666');
				 debugger;
				_.Dbroot.enum_child(_,'#enum');
				break;
				case 'enum':
				console.log(val);
				break;
			};
		});
	},
	*/
];};
if (typeof exports !== "undefined") exports.val = val;
else define({
	'val': val
});